package com.example.english.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.english.R;
import com.example.english.Utils;
import com.example.english.fragment.Tab1Fragment;
import com.example.english.fragment.Tab2Fragment;
import com.example.english.fragment.Tab3Fragment;

public class MainActivity extends AppCompatActivity {

    private Tab1Fragment fragment1 = new Tab1Fragment();
    private Tab2Fragment fragment2 = new Tab2Fragment();
    private Tab3Fragment fragment3 = new Tab3Fragment();

    private Fragment cusFragment ;// 当前的fragment

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Utils.setBarColor(this,true);
        init();
    }

    public void init() {
        if (fragment1 == null) {
            fragment1 = new Tab1Fragment();
        }
        if (!fragment1.isAdded()) {
            getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragment1).commit();
            // 记录当前Fragment
            cusFragment = fragment1;
        }
    }

    public void addOrShowFragment(Fragment fragment) {
        if (cusFragment == fragment)
            return;

        if (!fragment.isAdded()) { // 假设当前fragment未被加入，则加入到Fragment管理器中
            getSupportFragmentManager().beginTransaction().hide(cusFragment)
                    .add(R.id.fl_content, fragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(cusFragment).show(fragment).commit();
        }
        cusFragment = fragment;
    }



    public void tab1(View view){
        addOrShowFragment(fragment1);
    }

    public void tab2(View view){
        addOrShowFragment(fragment2);
    }

    public void tab3(View view){
        addOrShowFragment(fragment3);
    }

    public void tab4(View view){
        Intent it = new Intent(this ,PhotographActivity.class);
        startActivity(it);
    }

}
